_config = require './config'
_express = require 'express'
_cookieParser = require('cookie-parser')
_conn = require('./db-connect').conn()
_model = _conn.Model("statistics", _config.develop)
_crypto = require 'crypto'

_expires_out_time = 1000 * 60 * 60 * 24
app = _express()
app.use(_cookieParser())

#发送数据
sendData = (resp, referer)->
  sql =
    '''
      select
        (select count(*) from statistics where type = 'visit' and url = ?) as visit,
        (select count(*) from statistics where type = 'vote' and url = ?) as vote
    '''

  _model.sql(sql, [referer, referer])
    .then((data)->
        result = data[0]?[0]
        resulst = result or {}
        result.visit = if result.visit then result.visit + 100 else 100
        result.vote = if result.vote then result.vote + 50 else 50
        resp.send(result)
    )


#获取点赞和访问次数接口
#查cookie,是否本访问过,访问过者返回数据
#没有访问,则访问数据加1. 返回查询数据
app.get("/:any", (req, resp)->
  referer = req.get('referer')

  openid = req.cookies.openid

  #fingerprint = req.cookies.visit_fingerprint

  #return sendData(resp, referer) if fingerprint

  #fingerprint =  _uuid.v4()
  #resp.cookie('visit_fingerprint', fingerprint, {expires: new Date(Date.now() + _expires_out_time)})

  data =
    url: referer
    type: 'visit'
    openid: openid
    #fingerprint: fingerprint

  _model.save(data).then(()->
    sendData(resp, referer)
  )
)

app.post("/:any", (req, resp)->
  referer = req.get('referer') or ""
  openid = req.cookies.openid
  ip = req.headers['x-forwarded-for'] or req.connection.remoteAddress
  remoteIP = ip.replace('::ffff:', "")
  fingerprint =  _crypto.createHash('md5').update(remoteIP).digest('hex')
  sql = "
    select * from statistics where url = ? and (openid = ? or fingerprint = ?)
and type = 'vote'  "
  _model.sql(sql, [referer, openid, fingerprint]).then((data)->
    return null if data[0].length
    data =
      url: referer
      type: 'vote'
      openid: openid
      fingerprint: fingerprint

    _model.save(data)
  ).then(->
    resp.send({})
  )
)

app.listen(_config.port)